<template>
	<div class="app-container">
		<!-- 顶部导航栏 -->
		<header class="header">
			<div class="logo">
				<span class="iconify" data-icon="mdi:medal" style="color: white;"></span>
				运动会管理系统
			</div>
			<div class="flex-grow"></div>
			<div class="flex items-center gap-6">
				<div class="flex items-center gap-2">
					<img id="img-head" src="img/jstu1.webp">
					<span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
				</div>
				<div class="flex items-center gap-2">
					<a href="javascript:void(0)" class="denglu" @click="handleLogout">退出登录</a>
				</div>
			</div>
		</header>

		<!-- 左侧导航栏 -->
		<nav class="sidebar">
			<div class="menu-item" :class="{ active: $route.path === '/admin' }">
				<span class="iconify" data-icon="mdi:view-dashboard"></span>
				<a @click="$router.push('/admin')">系统管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/users' }">
				<span class="iconify" data-icon="mdi:account-group"></span>
				<a @click="$router.push('/admin/users')">用户管理</a>
			</div>
			<div class="menu-item active">
				<span class="iconify" data-icon="mdi:volunteer-activism"></span>
				志愿者管理
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/projects' }">
				<span class="iconify" data-icon="mdi:clipboard-list"></span>
				<a @click="$router.push('/admin/projects')">项目管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/schedule' }">
				<span class="iconify" data-icon="mdi:calendar-clock"></span>
				<a @click="$router.push('/admin/schedule')">赛程管理</a>
			</div>
			<div class="menu-item" :class="{ active: $route.path === '/admin/judges' }">
				<span class="iconify" data-icon="mdi:whistle"></span>
				<a @click="$router.push('/admin/judges')">裁判分配</a>
			</div>
		</nav>

		<!-- 主要内容 -->
		<main class="content">
			<!-- 面包屑导航 -->
			<div class="breadcrumb-container">
				<el-breadcrumb separator="/">
					<el-breadcrumb-item :to="{ path: '/admin' }">系统管理</el-breadcrumb-item>
					<el-breadcrumb-item>志愿者管理</el-breadcrumb-item>
					<el-breadcrumb-item>志愿者申请</el-breadcrumb-item>
				</el-breadcrumb>
			</div>

			<!-- 统计信息卡片 -->
			<div class="statistics-cards">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon pending">
									<span class="iconify" data-icon="mdi:clock-time-eight"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.pendingCount || 0 }}</div>
									<div class="stat-label">待审核申请</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon approved">
									<span class="iconify" data-icon="mdi:check-circle"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.approvedCount || 0 }}</div>
									<div class="stat-label">已通过申请</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon rejected">
									<span class="iconify" data-icon="mdi:close-circle"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.rejectedCount || 0 }}</div>
									<div class="stat-label">已拒绝申请</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="6">
						<el-card class="stat-card">
							<div class="stat-content">
								<div class="stat-icon total">
									<span class="iconify" data-icon="mdi:account-group"></span>
								</div>
								<div class="stat-info">
									<div class="stat-value">{{ statistics.totalCount || 0 }}</div>
									<div class="stat-label">总申请数</div>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>

			<!-- 志愿者申请表单 -->
			<div class="application-form-container">
				<el-card class="form-card">
					<template #header>
						<div class="card-header">
							<span class="card-title">志愿者申请</span>
							<el-button type="text" @click="toggleFormCollapse">
								<span class="iconify" :data-icon="isFormCollapsed ? 'mdi:chevron-down' : 'mdi:chevron-up'"></span>
							</el-button>
						</div>
					</template>
					<el-collapse-transition>
						<div v-show="!isFormCollapsed">
							<el-form :model="applicationForm" :rules="applicationFormRules" ref="applicationFormRef" label-width="120px">
								<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item label="姓名" prop="name">
											<el-input v-model="applicationForm.name" placeholder="请输入申请人姓名"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="性别" prop="gender">
											<el-select v-model="applicationForm.gender" placeholder="请选择性别" style="width: 100%">
												<el-option label="男" value="男"></el-option>
												<el-option label="女" value="女"></el-option>
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item label="学号" prop="studentId">
											<el-input v-model="applicationForm.studentId" placeholder="请输入学号"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="班级" prop="className">
											<el-input v-model="applicationForm.className" placeholder="请输入班级"></el-input>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item label="学院" prop="department">
											<el-input v-model="applicationForm.department" placeholder="请输入学院"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="联系电话" prop="phone">
											<el-input v-model="applicationForm.phone" placeholder="请输入联系电话"></el-input>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item label="邮箱" prop="email">
											<el-input v-model="applicationForm.email" placeholder="请输入邮箱"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="志愿部门" prop="preferredDepartment">
											<el-select v-model="applicationForm.preferredDepartment" placeholder="请选择志愿部门" style="width: 100%">
												<el-option label="竞赛组" value="竞赛组"></el-option>
												<el-option label="后勤组" value="后勤组"></el-option>
												<el-option label="宣传组" value="宣传组"></el-option>
												<el-option label="安全组" value="安全组"></el-option>
												<el-option label="医疗组" value="医疗组"></el-option>
												<el-option label="接待组" value="接待组"></el-option>
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="24">
										<el-form-item label="个人特长" prop="skills">
											<el-input
												v-model="applicationForm.skills"
												type="textarea"
												:rows="3"
												placeholder="请输入个人特长或相关技能">
											</el-input>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="24">
										<el-form-item label="申请理由" prop="reason">
											<el-input
												v-model="applicationForm.reason"
												type="textarea"
												:rows="4"
												placeholder="请输入申请志愿者的理由">
											</el-input>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item label="可服务时间" prop="availableTime">
											<el-date-picker
												v-model="applicationForm.availableTime"
												type="daterange"
												range-separator="至"
												start-placeholder="开始日期"
												end-placeholder="结束日期"
												style="width: 100%">
											</el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="每日时间段" prop="dailyTimeRange">
											<el-select v-model="applicationForm.dailyTimeRange" placeholder="请选择每日时间段" style="width: 100%">
												<el-option label="上午" value="上午"></el-option>
												<el-option label="下午" value="下午"></el-option>
												<el-option label="晚上" value="晚上"></el-option>
												<el-option label="全天" value="全天"></el-option>
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
								<el-form-item>
									<el-button type="primary" @click="submitApplication" :loading="submitLoading">提交申请</el-button>
									<el-button @click="resetApplicationForm">重置表单</el-button>
								</el-form-item>
							</el-form>
						</div>
					</el-collapse-transition>
				</el-card>
			</div>

			<!-- 搜索筛选区域 -->
			<div class="search-bar">
				<el-form :inline="true" :model="searchForm" size="small">
					<el-form-item label="姓名">
						<el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 150px"></el-input>
					</el-form-item>
					<el-form-item label="学号">
						<el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable style="width: 150px"></el-input>
					</el-form-item>
					<el-form-item label="班级">
						<el-input v-model="searchForm.className" placeholder="请输入班级" clearable style="width: 150px"></el-input>
					</el-form-item>
					<el-form-item label="志愿部门">
						<el-select v-model="searchForm.preferredDepartment" placeholder="请选择志愿部门" clearable style="width: 150px">
							<el-option label="竞赛组" value="竞赛组"></el-option>
							<el-option label="后勤组" value="后勤组"></el-option>
							<el-option label="宣传组" value="宣传组"></el-option>
							<el-option label="安全组" value="安全组"></el-option>
							<el-option label="医疗组" value="医疗组"></el-option>
							<el-option label="接待组" value="接待组"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="审核状态">
						<el-select v-model="searchForm.status" placeholder="请选择审核状态" clearable style="width: 130px">
							<el-option label="待审核" value="pending"></el-option>
							<el-option label="已通过" value="approved"></el-option>
							<el-option label="已拒绝" value="rejected"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="申请时间">
						<el-date-picker
							v-model="searchForm.dateRange"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							style="width: 220px"
							value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch" :loading="loading">
							<i class="el-icon-search"></i> 搜索
						</el-button>
						<el-button @click="handleReset">
							<i class="el-icon-refresh"></i> 重置
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 申请列表表格 -->
			<div class="table-container">
				<div class="table-header">
					<div class="table-title">申请列表</div>
					<div class="table-actions">
						<el-button type="success" size="small" @click="handleBatchApprove" :disabled="selectedApplications.length === 0">
							<i class="el-icon-check"></i> 批量通过
						</el-button>
						<el-button type="danger" size="small" @click="handleBatchReject" :disabled="selectedApplications.length === 0">
							<i class="el-icon-close"></i> 批量拒绝
						</el-button>
						<el-button type="info" size="small" @click="exportApplications">
							<i class="el-icon-download"></i> 导出数据
						</el-button>
					</div>
				</div>
				<el-table
					:data="tableData"
					v-loading="loading"
					stripe
					border
					style="width: 100%"
					@selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column prop="id" label="申请ID" width="80" align="center"></el-table-column>
					<el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
					<el-table-column prop="gender" label="性别" width="60" align="center"></el-table-column>
					<el-table-column prop="studentId" label="学号" width="120" align="center"></el-table-column>
					<el-table-column prop="className" label="班级" width="150" align="center"></el-table-column>
					<el-table-column prop="department" label="学院" width="150" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="preferredDepartment" label="志愿部门" width="100" align="center">
						<template #default="scope">
							<el-tag size="small" :type="getDepartmentTagType(scope.row.preferredDepartment)">
								{{ scope.row.preferredDepartment }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="phone" label="联系电话" width="130" align="center"></el-table-column>
					<el-table-column prop="status" label="审核状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getStatusTagType(scope.row.status)" size="small">
								{{ getStatusText(scope.row.status) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="applicationTime" label="申请时间" width="180" align="center">
						<template #default="scope">
							{{ formatDateTime(scope.row.applicationTime) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" width="250" align="center" fixed="right">
						<template #default="scope">
							<el-button-group size="mini">
								<el-button type="primary" icon="el-icon-view" @click="handleViewDetail(scope.row)">详情</el-button>
								<el-button
									v-if="scope.row.status === 'pending'"
									type="success"
									icon="el-icon-check"
									@click="handleApprove(scope.row)">
									通过
								</el-button>
								<el-button
									v-if="scope.row.status === 'pending'"
									type="danger"
									icon="el-icon-close"
									@click="handleReject(scope.row)">
									拒绝
								</el-button>
								<el-button
									type="warning"
									icon="el-icon-edit"
									@click="handleEdit(scope.row)">
									编辑
								</el-button>
							</el-button-group>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页控制 -->
				<div class="pagination-container">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pagination.currentPage"
						:page-sizes="[10, 20, 50, 100]"
						:page-size="pagination.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="pagination.total">
					</el-pagination>
				</div>

				<!-- 批量操作 -->
				<div class="batch-operations" v-if="selectedApplications.length > 0">
					<span>已选择 {{ selectedApplications.length }} 项</span>
					<el-button type="success" size="small" @click="handleBatchApprove">批量通过</el-button>
					<el-button type="danger" size="small" @click="handleBatchReject">批量拒绝</el-button>
				</div>
			</div>

			<!-- 申请详情对话框 -->
			<el-dialog
				title="申请详情"
				v-model="detailDialogVisible"
				width="800px"
				:before-close="handleDetailClose">
				<div v-if="currentApplication" class="detail-content">
					<el-descriptions :column="2" border>
						<el-descriptions-item label="申请ID">{{ currentApplication.id }}</el-descriptions-item>
						<el-descriptions-item label="姓名">{{ currentApplication.name }}</el-descriptions-item>
						<el-descriptions-item label="性别">{{ currentApplication.gender }}</el-descriptions-item>
						<el-descriptions-item label="学号">{{ currentApplication.studentId }}</el-descriptions-item>
						<el-descriptions-item label="班级">{{ currentApplication.className }}</el-descriptions-item>
						<el-descriptions-item label="学院">{{ currentApplication.department }}</el-descriptions-item>
						<el-descriptions-item label="联系电话">{{ currentApplication.phone }}</el-descriptions-item>
						<el-descriptions-item label="邮箱">{{ currentApplication.email }}</el-descriptions-item>
						<el-descriptions-item label="志愿部门">{{ currentApplication.preferredDepartment }}</el-descriptions-item>
						<el-descriptions-item label="审核状态">
							<el-tag :type="getStatusTagType(currentApplication.status)">
								{{ getStatusText(currentApplication.status) }}
							</el-tag>
						</el-descriptions-item>
						<el-descriptions-item label="申请时间">{{ formatDateTime(currentApplication.applicationTime) }}</el-descriptions-item>
						<el-descriptions-item label="可服务时间" :span="2">
							{{ currentApplication.availableTimeStart }} 至 {{ currentApplication.availableTimeEnd }}
						</el-descriptions-item>
						<el-descriptions-item label="每日时间段">{{ currentApplication.dailyTimeRange }}</el-descriptions-item>
						<el-descriptions-item label="个人特长" :span="2">{{ currentApplication.skills || '无' }}</el-descriptions-item>
						<el-descriptions-item label="申请理由" :span="2">{{ currentApplication.reason }}</el-descriptions-item>
						<el-descriptions-item v-if="currentApplication.reviewComment" label="审核意见" :span="2">{{ currentApplication.reviewComment }}</el-descriptions-item>
						<el-descriptions-item v-if="currentApplication.reviewTime" label="审核时间">{{ formatDateTime(currentApplication.reviewTime) }}</el-descriptions-item>
					</el-descriptions>
				</div>
			</el-dialog>

			<!-- 审核对话框 -->
			<el-dialog
				:title="reviewDialogTitle"
				v-model="reviewDialogVisible"
				width="500px"
				:before-close="handleReviewClose">
				<el-form :model="reviewForm" :rules="reviewFormRules" ref="reviewFormRef" label-width="100px">
					<el-form-item label="审核结果" prop="reviewResult">
						<el-radio-group v-model="reviewForm.reviewResult">
							<el-radio label="approved">通过</el-radio>
							<el-radio label="rejected">拒绝</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="审核意见" prop="reviewComment">
						<el-input
							v-model="reviewForm.reviewComment"
							type="textarea"
							:rows="4"
							placeholder="请输入审核意见">
						</el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleReviewClose">取消</el-button>
						<el-button type="primary" @click="confirmReview" :loading="reviewLoading">确定</el-button>
					</div>
				</template>
			</el-dialog>

			<!-- 编辑申请对话框 -->
			<el-dialog
				title="编辑申请"
				v-model="editDialogVisible"
				width="600px"
				:before-close="handleEditClose">
				<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="姓名" prop="name">
								<el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="性别" prop="gender">
								<el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
									<el-option label="男" value="男"></el-option>
									<el-option label="女" value="女"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="学号" prop="studentId">
								<el-input v-model="editForm.studentId" placeholder="请输入学号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="班级" prop="className">
								<el-input v-model="editForm.className" placeholder="请输入班级"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="学院" prop="department">
								<el-input v-model="editForm.department" placeholder="请输入学院"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系电话" prop="phone">
								<el-input v-model="editForm.phone" placeholder="请输入联系电话"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="邮箱" prop="email">
								<el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="志愿部门" prop="preferredDepartment">
								<el-select v-model="editForm.preferredDepartment" placeholder="请选择志愿部门" style="width: 100%">
									<el-option label="竞赛组" value="竞赛组"></el-option>
									<el-option label="后勤组" value="后勤组"></el-option>
									<el-option label="宣传组" value="宣传组"></el-option>
									<el-option label="安全组" value="安全组"></el-option>
									<el-option label="医疗组" value="医疗组"></el-option>
									<el-option label="接待组" value="接待组"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="个人特长" prop="skills">
						<el-input
							v-model="editForm.skills"
							type="textarea"
							:rows="3"
							placeholder="请输入个人特长或相关技能">
						</el-input>
					</el-form-item>
					<el-form-item label="申请理由" prop="reason">
						<el-input
							v-model="editForm.reason"
							type="textarea"
							:rows="4"
							placeholder="请输入申请志愿者的理由">
						</el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="handleEditClose">取消</el-button>
						<el-button type="primary" @click="saveEdit" :loading="editLoading">保存</el-button>
					</div>
				</template>
			</el-dialog>
		</main>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
	submitVolunteerApplication,
	getVolunteerApplications,
	getApplicationById,
	reviewVolunteerApplication,
	getVolunteerStatistics
} from '@/api/volunteer'
import { useAuthStore } from '@/stores/auth'

export default {
	name: 'VolunteerApplication',
	setup() {
		// 组件引用
		const applicationFormRef = ref(null)
		const reviewFormRef = ref(null)
		const editFormRef = ref(null)

		// 当前用户信息
		const currentUser = ref(null)

		// 统计信息
		const statistics = reactive({
			pendingCount: 0,
			approvedCount: 0,
			rejectedCount: 0,
			totalCount: 0
		})

		// 申请表单相关
		const isFormCollapsed = ref(false)
		const submitLoading = ref(false)
		const applicationForm = reactive({
			name: '',
			gender: '',
			studentId: '',
			className: '',
			department: '',
			phone: '',
			email: '',
			preferredDepartment: '',
			skills: '',
			reason: '',
			availableTime: [],
			dailyTimeRange: ''
		})

		// 自定义验证规则
		const validatePhone = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入联系电话'))
			} else if (!/^1[3-9]\d{9}$/.test(value)) {
				callback(new Error('请输入正确的手机号'))
			} else {
				callback()
			}
		}

		const validateEmail = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入邮箱'))
			} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
				callback(new Error('请输入正确的邮箱格式'))
			} else {
				callback()
			}
		}

		const applicationFormRules = {
			name: [
				{ required: true, message: '请输入姓名', trigger: 'blur' },
				{ min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
			],
			gender: [
				{ required: true, message: '请选择性别', trigger: 'change' }
			],
			studentId: [
				{ required: true, message: '请输入学号', trigger: 'blur' }
			],
			className: [
				{ required: true, message: '请输入班级', trigger: 'blur' }
			],
			department: [
				{ required: true, message: '请输入学院', trigger: 'blur' }
			],
			phone: [
				{ validator: validatePhone, trigger: 'blur' }
			],
			email: [
				{ validator: validateEmail, trigger: 'blur' }
			],
			preferredDepartment: [
				{ required: true, message: '请选择志愿部门', trigger: 'change' }
			],
			reason: [
				{ required: true, message: '请输入申请理由', trigger: 'blur' },
				{ min: 10, max: 500, message: '申请理由长度在 10 到 500 个字符', trigger: 'blur' }
			],
			availableTime: [
				{ required: true, message: '请选择可服务时间', trigger: 'change' }
			],
			dailyTimeRange: [
				{ required: true, message: '请选择每日时间段', trigger: 'change' }
			]
		}

		// 搜索表单
		const searchForm = reactive({
			name: '',
			studentId: '',
			className: '',
			preferredDepartment: '',
			status: '',
			dateRange: []
		})

		// 表格数据
		const tableData = ref([])
		const loading = ref(false)

		// 分页信息
		const pagination = reactive({
			currentPage: 1,
			pageSize: 10,
			total: 0
		})

		// 选中的申请
		const selectedApplications = ref([])

		// 详情对话框
		const detailDialogVisible = ref(false)
		const currentApplication = ref(null)

		// 审核对话框
		const reviewDialogVisible = ref(false)
		const reviewDialogTitle = ref('审核申请')
		const reviewLoading = ref(false)
		const currentReviewApplication = ref(null)
		const reviewForm = reactive({
			reviewResult: 'approved',
			reviewComment: ''
		})

		const reviewFormRules = {
			reviewResult: [
				{ required: true, message: '请选择审核结果', trigger: 'change' }
			],
			reviewComment: [
				{ required: true, message: '请输入审核意见', trigger: 'blur' },
				{ min: 5, max: 200, message: '审核意见长度在 5 到 200 个字符', trigger: 'blur' }
			]
		}

		// 编辑对话框
		const editDialogVisible = ref(false)
		const editLoading = ref(false)
		const editForm = reactive({
			id: null,
			name: '',
			gender: '',
			studentId: '',
			className: '',
			department: '',
			phone: '',
			email: '',
			preferredDepartment: '',
			skills: '',
			reason: ''
		})

		const editFormRules = {
			name: [
				{ required: true, message: '请输入姓名', trigger: 'blur' }
			],
			gender: [
				{ required: true, message: '请选择性别', trigger: 'change' }
			],
			studentId: [
				{ required: true, message: '请输入学号', trigger: 'blur' }
			],
			className: [
				{ required: true, message: '请输入班级', trigger: 'blur' }
			],
			department: [
				{ required: true, message: '请输入学院', trigger: 'blur' }
			],
			phone: [
				{ validator: validatePhone, trigger: 'blur' }
			],
			email: [
				{ validator: validateEmail, trigger: 'blur' }
			],
			preferredDepartment: [
				{ required: true, message: '请选择志愿部门', trigger: 'change' }
			],
			reason: [
				{ required: true, message: '请输入申请理由', trigger: 'blur' }
			]
		}

		// 加载数据
		const loadData = async () => {
			loading.value = true
			try {
				const params = {
					...searchForm,
					currentPage: pagination.currentPage,
					pageSize: pagination.pageSize
				}

				// 处理日期范围
				if (searchForm.dateRange && searchForm.dateRange.length === 2) {
					params.startDate = searchForm.dateRange[0]
					params.endDate = searchForm.dateRange[1]
				}

				const response = await getVolunteerApplications(pagination.currentPage, pagination.pageSize, params)

				if (response.code === 200) {
					tableData.value = response.data.records
					pagination.total = response.data.total
				} else {
					ElMessage.error(response.message || '获取数据失败')
				}
			} catch (error) {
				console.error('获取申请数据失败:', error)
				ElMessage.error('获取数据失败')
			} finally {
				loading.value = false
			}
		}

		// 加载统计信息
		const loadStatistics = async () => {
			try {
				const response = await getVolunteerStatistics()
				if (response.code === 200) {
					Object.assign(statistics, response.data)
				}
			} catch (error) {
				console.error('获取统计信息失败:', error)
			}
		}

		// 提交申请
		const submitApplication = () => {
			if (!applicationFormRef.value) return
			applicationFormRef.value.validate(async (valid) => {
				if (valid) {
					submitLoading.value = true
					try {
						const applicationData = {
							...applicationForm,
							availableTimeStart: applicationForm.availableTime[0],
							availableTimeEnd: applicationForm.availableTime[1]
						}
						delete applicationData.availableTime

						const response = await submitVolunteerApplication(applicationData)
						if (response.code === 200) {
							ElMessage.success('申请提交成功')
							resetApplicationForm()
							loadData()
							loadStatistics()
						} else {
							ElMessage.error(response.message || '申请提交失败')
						}
					} catch (error) {
						console.error('提交申请失败:', error)
						ElMessage.error('申请提交失败')
					} finally {
						submitLoading.value = false
					}
				}
			})
		}

		// 重置申请表单
		const resetApplicationForm = () => {
			if (applicationFormRef.value) {
				applicationFormRef.value.resetFields()
			}
			Object.assign(applicationForm, {
				name: '',
				gender: '',
				studentId: '',
				className: '',
				department: '',
				phone: '',
				email: '',
				preferredDepartment: '',
				skills: '',
				reason: '',
				availableTime: [],
				dailyTimeRange: ''
			})
		}

		// 切换表单折叠状态
		const toggleFormCollapse = () => {
			isFormCollapsed.value = !isFormCollapsed.value
		}

		// 搜索
		const handleSearch = () => {
			pagination.currentPage = 1
			loadData()
		}

		// 重置搜索
		const handleReset = () => {
			Object.assign(searchForm, {
				name: '',
				studentId: '',
				className: '',
				preferredDepartment: '',
				status: '',
				dateRange: []
			})
			handleSearch()
		}

		// 分页大小改变
		const handleSizeChange = (val) => {
			pagination.pageSize = val
			loadData()
		}

		// 当前页改变
		const handleCurrentChange = (val) => {
			pagination.currentPage = val
			loadData()
		}

		// 表格选择改变
		const handleSelectionChange = (selection) => {
			selectedApplications.value = selection
		}

		// 查看详情
		const handleViewDetail = async (row) => {
			try {
				const response = await getApplicationById(row.id)
				if (response.code === 200) {
					currentApplication.value = response.data
					detailDialogVisible.value = true
				} else {
					ElMessage.error(response.message || '获取申请详情失败')
				}
			} catch (error) {
				console.error('获取申请详情失败:', error)
				ElMessage.error('获取申请详情失败')
			}
		}

		// 审核申请
		const handleReview = (row, result = null) => {
			currentReviewApplication.value = row
			reviewDialogTitle.value = result ? '批量审核申请' : '审核申请'
			Object.assign(reviewForm, {
				reviewResult: result || (row.status === 'pending' ? 'approved' : 'rejected'),
				reviewComment: ''
			})
			reviewDialogVisible.value = true
		}

		// 通过申请
		const handleApprove = (row) => {
			handleReview(row, 'approved')
		}

		// 拒绝申请
		const handleReject = (row) => {
			handleReview(row, 'rejected')
		}

		// 确认审核
		const confirmReview = () => {
			if (!reviewFormRef.value) return
			reviewFormRef.value.validate(async (valid) => {
				if (valid) {
					reviewLoading.value = true
					try {
						const reviewData = {
							status: reviewForm.reviewResult,
							reviewComment: reviewForm.reviewComment
						}

						const response = await reviewVolunteerApplication(currentReviewApplication.value.id, reviewData)
						if (response.code === 200) {
							ElMessage.success('审核成功')
							reviewDialogVisible.value = false
							loadData()
							loadStatistics()
						} else {
							ElMessage.error(response.message || '审核失败')
						}
					} catch (error) {
						console.error('审核失败:', error)
						ElMessage.error('审核失败')
					} finally {
						reviewLoading.value = false
					}
				}
			})
		}

		// 批量审核
		const handleBatchReview = (result) => {
			if (selectedApplications.value.length === 0) {
				ElMessage.warning('请选择要审核的申请')
				return
			}

			ElMessageBox.confirm(`确定要${result === 'approved' ? '通过' : '拒绝'}选中的 ${selectedApplications.value.length} 个申请吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				try {
					// 这里应该调用批量审核的API，但现有API只支持单个审核，所以循环调用
					const promises = selectedApplications.value.map(application => {
						return reviewVolunteerApplication(application.id, {
							status: result,
							reviewComment: `批量${result === 'approved' ? '通过' : '拒绝'}`
						})
					})

					await Promise.all(promises)
					ElMessage.success(`批量${result === 'approved' ? '通过' : '拒绝'}成功`)
					loadData()
					loadStatistics()
					selectedApplications.value = []
				} catch (error) {
					console.error(`批量${result === 'approved' ? '通过' : '拒绝'}失败:`, error)
					ElMessage.error(`批量${result === 'approved' ? '通过' : '拒绝'}失败`)
				}
			})
		}

		// 批量通过
		const handleBatchApprove = () => {
			handleBatchReview('approved')
		}

		// 批量拒绝
		const handleBatchReject = () => {
			handleBatchReview('rejected')
		}

		// 编辑申请
		const handleEdit = (row) => {
			Object.assign(editForm, { ...row })
			editDialogVisible.value = true
		}

		// 保存编辑
		const saveEdit = () => {
			if (!editFormRef.value) return
			editFormRef.value.validate(async (valid) => {
				if (valid) {
					editLoading.value = true
					try {
						// 这里应该调用更新申请的API
						// const response = await updateApplication(editForm)
						// 由于没有对应的API，这里先模拟成功
						ElMessage.success('更新成功')
						editDialogVisible.value = false
						loadData()
					} catch (error) {
						console.error('更新申请失败:', error)
						ElMessage.error('更新失败')
					} finally {
						editLoading.value = false
					}
				}
			})
		}

		// 导出申请数据
		const exportApplications = () => {
			// 这里应该调用导出数据的API
			ElMessage.info('导出功能开发中...')
		}

		// 关闭详情对话框
		const handleDetailClose = () => {
			detailDialogVisible.value = false
			currentApplication.value = null
		}

		// 关闭审核对话框
		const handleReviewClose = () => {
			reviewDialogVisible.value = false
			currentReviewApplication.value = null
			if (reviewFormRef.value) {
				reviewFormRef.value.resetFields()
			}
		}

		// 关闭编辑对话框
		const handleEditClose = () => {
			editDialogVisible.value = false
			if (editFormRef.value) {
				editFormRef.value.resetFields()
			}
		}

		// 退出登录
		const handleLogout = () => {
			const authStore = useAuthStore()
			ElMessageBox.confirm('确定要退出登录吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				// 使用Pinia的logout方法
				authStore.logout()
				// 跳转到登录页
				window.location.href = '/login'
			})
		}

		// 获取状态标签类型
		const getStatusTagType = (status) => {
			const typeMap = {
				'pending': 'warning',
				'approved': 'success',
				'rejected': 'danger'
			}
			return typeMap[status] || 'info'
		}

		// 获取状态文本
		const getStatusText = (status) => {
			const textMap = {
				'pending': '待审核',
				'approved': '已通过',
				'rejected': '已拒绝'
			}
			return textMap[status] || '未知'
		}

		// 获取部门标签类型
		const getDepartmentTagType = (department) => {
			const typeMap = {
				'竞赛组': 'primary',
				'后勤组': 'success',
				'宣传组': 'warning',
				'安全组': 'danger',
				'医疗组': 'info',
				'接待组': 'primary'
			}
			return typeMap[department] || 'info'
		}

		// 格式化日期时间
		const formatDateTime = (dateTime) => {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		}

		// 生命周期
		onMounted(() => {
			// 获取当前用户信息
			currentUser.value = JSON.parse(localStorage.getItem('user')) || { realName: '管理员' }
			// 加载数据
			loadData()
			loadStatistics()
		})

		return {
			// Refs
			applicationFormRef,
			reviewFormRef,
			editFormRef,

			// Reactive data
			currentUser,
			statistics,
			isFormCollapsed,
			submitLoading,
			applicationForm,
			applicationFormRules,
			searchForm,
			tableData,
			loading,
			pagination,
			selectedApplications,
			detailDialogVisible,
			currentApplication,
			reviewDialogVisible,
			reviewDialogTitle,
			reviewLoading,
			currentReviewApplication,
			reviewForm,
			reviewFormRules,
			editDialogVisible,
			editLoading,
			editForm,
			editFormRules,

			// Methods
			loadData,
			loadStatistics,
			submitApplication,
			resetApplicationForm,
			toggleFormCollapse,
			handleSearch,
			handleReset,
			handleSizeChange,
			handleCurrentChange,
			handleSelectionChange,
			handleViewDetail,
			handleReview,
			handleApprove,
			handleReject,
			confirmReview,
			handleBatchReview,
			handleBatchApprove,
			handleBatchReject,
			handleEdit,
			saveEdit,
			exportApplications,
			handleDetailClose,
			handleReviewClose,
			handleEditClose,
			handleLogout,
			getStatusTagType,
			getStatusText,
			getDepartmentTagType,
			formatDateTime
		}
	}
}
</script>

<style scoped>
/* 基础样式 */
* {
	font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

body {
	background-color: #f0f2f5;
	color: #1a1a1a;
	margin: 0;
}

/* 容器布局 */
.app-container {
	max-width: 1440px;
	margin: 0 auto;
	display: grid;
	grid-template-columns: 240px 1fr;
	grid-template-rows: 64px 1fr;
	min-height: 100vh;
	background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
	grid-column: 1 / -1;
	background-color: #2C5AA0;
	display: flex;
	align-items: center;
	padding: 0 24px;
}

.logo {
	font-size: 18px;
	font-weight: bold;
	color: white;
	display: flex;
	align-items: center;
	gap: 8px;
}

.flex-grow {
	flex-grow: 1;
}

.flex {
	display: flex;
}

.items-center {
	align-items: center;
}

.gap-6 {
	gap: 24px;
}

.gap-2 {
	gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
	background-color: white;
	padding: 16px 0;
	border-right: 1px solid #e4e7ed;
}

.menu-item {
	padding: 12px 24px;
	color: #555;
	display: flex;
	align-items: center;
	gap: 12px;
	transition: all 0.3s;
	cursor: pointer;
}

.menu-item.active,
.menu-item:hover {
	background-color: #e8eff9;
	color: #2C5AA0;
	border-right: 3px solid #2C5AA0;
}

/* 主内容区 */
.content {
	padding: 24px;
	display: grid;
	grid-template-rows: auto auto auto auto 1fr;
	gap: 20px;
	overflow-y: auto;
}

/* 面包屑导航 */
.breadcrumb-container {
	background: white;
	padding: 16px 24px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
}

/* 统计卡片 */
.statistics-cards {
	margin-bottom: 0;
}

.stat-card {
	cursor: pointer;
	transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-content {
	display: flex;
	align-items: center;
	gap: 16px;
}

.stat-icon {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-size: 24px;
}

.stat-icon.pending {
	background: linear-gradient(135deg, #F59E0B, #D97706);
}

.stat-icon.approved {
	background: linear-gradient(135deg, #10B981, #059669);
}

.stat-icon.rejected {
	background: linear-gradient(135deg, #EF4444, #DC2626);
}

.stat-icon.total {
	background: linear-gradient(135deg, #3B82F6, #2563EB);
}

.stat-info {
	flex: 1;
}

.stat-value {
	font-size: 28px;
	font-weight: bold;
	color: #1f2937;
	line-height: 1;
}

.stat-label {
	font-size: 14px;
	color: #6b7280;
	margin-top: 4px;
}

/* 申请表单容器 */
.application-form-container {
	margin-bottom: 0;
}

.form-card .card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.card-title {
	font-weight: 600;
	color: #1f2937;
}

/* 搜索区域 */
.search-bar {
	background: white;
	padding: 24px;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	margin-bottom: 0;
}

/* 表格容器 */
.table-container {
	background: white;
	border-radius: 8px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	border: 1px solid #e4e7ed;
	padding: 24px;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.table-title {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
}

.table-actions {
	display: flex;
	gap: 8px;
}

/* 分页容器 */
.pagination-container {
	margin-top: 20px;
	text-align: right;
}

/* 批量操作 */
.batch-operations {
	margin-top: 16px;
	padding: 12px;
	background-color: #f5f7fa;
	border-radius: 4px;
	display: flex;
	align-items: center;
	gap: 12px;
}

.batch-operations span {
	font-weight: 500;
	color: #606266;
}

/* 详情内容 */
.detail-content {
	padding: 16px 0;
}

/* 头像和退出登录 */
#img-head {
	height: 40px;
	width: 40px;
	border-radius: 50px;
}

.denglu {
	color: white;
	font-size: 15px;
	text-decoration: none;
}

.denglu:hover {
	color: #F44346;
}

.text-sm {
	font-size: 14px;
}

.text-white {
	color: white;
}

/* Element UI 样式调整 */
.el-table {
	margin-top: 16px;
}

.el-table th {
	background-color: #fafafa !important;
}

.el-form-item {
	margin-bottom: 0;
}

.el-card {
	border-radius: 8px;
	border: 1px solid #e4e7ed;
}

.el-descriptions {
	margin-top: 16px;
}

.el-descriptions__label {
	font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
	.statistics-cards .el-col {
		margin-bottom: 16px;
	}

	.search-bar .el-form-item {
		margin-bottom: 10px;
	}
}

@media (max-width: 768px) {
	.app-container {
		grid-template-columns: 1fr;
	}

	.sidebar {
		display: none;
	}

	.table-header {
		flex-direction: column;
		gap: 12px;
		align-items: flex-start;
	}

	.table-actions {
		width: 100%;
		justify-content: flex-start;
		flex-wrap: wrap;
	}

	.el-form--inline .el-form-item {
		display: block;
		margin-right: 0;
		margin-bottom: 10px;
	}

	.search-bar .el-select,
	.search-bar .el-input {
		width: 100% !important;
	}

	.application-form-container .el-col {
		margin-bottom: 10px;
	}
}

@media (max-width: 480px) {
	.content {
		padding: 12px;
	}

	.statistics-cards .el-col {
		margin-bottom: 12px;
	}

	.el-card {
		margin-bottom: 12px;
	}

	.table-container {
		padding: 12px;
		overflow-x: auto;
	}

	.el-table {
		min-width: 800px;
	}
}

/* 加载状态增强 */
.el-loading-mask {
	background-color: rgba(255, 255, 255, 0.8);
	backdrop-filter: blur(2px);
}

.el-button.is-loading {
	position: relative;
}

.el-button.is-loading:before {
	content: "";
	position: absolute;
	top: -1px;
	left: -1px;
	right: -1px;
	bottom: -1px;
	border-radius: inherit;
	background-color: rgba(255, 255, 255, 0.35);
}

/* 表格悬停效果增强 */
.el-table--enable-row-hover .el-table__body tr:hover > td {
	background-color: #f5f7fa;
	transition: background-color 0.25s ease;
}

/* 表单交互增强 */
.el-form-item.is-error .el-input__inner {
	border-color: #f56c6c;
	box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
	transition: all 0.3s;
}

.el-form-item.is-success .el-input__inner {
	border-color: #67c23a;
	box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
	transition: all 0.3s;
}

/* 对话框动画增强 */
.el-dialog {
	transition: all 0.3s ease;
}

.el-dialog__wrapper {
	backdrop-filter: blur(3px);
}

/* 分页组件增强 */
.el-pagination {
	text-align: center;
	margin-top: 20px;
}

.el-pagination .el-pager li {
	border-radius: 4px;
	transition: all 0.3s;
}

.el-pagination .el-pager li:hover {
	transform: translateY(-1px);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 按钮交互增强 */
.el-button {
	transition: all 0.3s ease;
	border-radius: 6px;
	font-weight: 500;
}

.el-button:hover {
	transform: translateY(-1px);
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.el-button:active {
	transform: translateY(0);
}

/* 搜索栏增强 */
.search-bar {
	position: sticky;
	top: 0;
	z-index: 10;
	background: white;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 卡片增强 */
.el-card {
	transition: all 0.3s ease;
	border-radius: 8px;
}

.el-card:hover {
	box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

/* 标签增强 */
.el-tag {
	transition: all 0.3s ease;
	border-radius: 4px;
}

.el-tag:hover {
	transform: scale(1.05);
}

/* 面包屑导航增强 */
.el-breadcrumb {
	padding: 12px 16px;
	background-color: #f8f9fa;
	border-radius: 6px;
	margin-bottom: 16px;
}

/* 表单折叠动画 */
.el-collapse-transition {
	transition: all 0.3s ease-in-out;
}

/* 批量操作区域增强 */
.batch-operations {
	background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
	border: 1px solid #dee2e6;
	border-radius: 6px;
	padding: 12px 16px;
	margin-top: 16px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
</style>